package com.qf.ayc.user.controller;

import com.qf.ayc.orders.entity.Orders;
import com.qf.ayc.product.entity.Product;
import com.qf.ayc.user.entity.Users;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.qf.ayc.user.entity.Users;
import com.qf.ayc.user.mapper.UsersMapper;
import com.qf.ayc.user.service.IUsersService;
import com.qf.ayc.user.vo.LoginVo;
import com.qf.ayc.utils.ResultVo;
import com.qf.ayc.utils.ResultVo;
import lombok.extern.slf4j.Slf4j;
import org.apache.catalina.User;
import org.apache.tomcat.util.http.fileupload.IOUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.UUID;
import org.springframework.util.ResourceUtils;
import org.springframework.core.io.Resource;
import org.springframework.core.io.UrlResource;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;
import java.net.MalformedURLException;
/**
 * <p>
 * 前端控制器
 * </p>
 * 登录请求路径localhost:8083/users/login?username=bf&password=123
 * 注册localhost:8082/users/register?username=西瓜大炸弹&password=123&nickname=超级大西瓜
 *
 * @author BeautyFairy
 * @since 2024-02-20
 */
@RestController
@CrossOrigin
@Slf4j
@RequestMapping("/users")
public class UsersController {

    @Autowired
    private IUsersService iUsersService;

    @Autowired
    private UsersMapper usersMapper;

    @PostMapping("/send")
    private ResultVo send(String id){
        Users users = usersMapper.selectById(id);
        String data = users.getCheckedkeys();

        return ResultVo.ok("200", "发送权限数据成功", data);

    }

    //图片的第一次上传
    @PostMapping("/upattr")
    private String upattr(@RequestParam("file") MultipartFile file) {
        if (file.isEmpty()) {
//            return ResultVo.ok("-1", "图片为空，请选择图片");
            return "图片为空，请选择图片";
        }
        String uuid = UUID.randomUUID().toString().replace("-", "").substring(0, 8);

        String fileName = uuid+file.getOriginalFilename()  ;
        // 上传文件路径的处理，相对项目jar包的部署路径存放upload目录
        String filePath = "/opt/userattr/";
        File dir = new File(filePath);
        if (!dir.exists()) {
            dir.mkdir();
        }
        String dest = filePath + File.separator + fileName;
        log.debug("dest={}", dest);
        try {

            file.transferTo(new File(dest));
            log.info("上传成功");
//            return ResultVo.ok("200", "图片修改成功","http://182.92.162.156:8083/"+dest);
            return  fileName;
        } catch (IOException e) {
            log.error(e.toString(), e);
        }
//        return ResultVo.ok("200", "图片修改失败");
        return "图片修改失败";
    }

    //图片的第二次提交
    @GetMapping("/changeattr")
    public ResultVo changeattr(String oriusername,String username, String attrpath) {
        //先把用户传过来的新名字，直接去数据库找是否重名4
        log.info("原名{}修改名{}头像名{}",oriusername,username,attrpath);
        Users one1 = iUsersService.getOne(new QueryWrapper<Users>().eq("username", username));
        log.info("修改的名字是否有东西{}",one1);
        //如果找不到，就是没有重名的，可以根据原来的名字找到对应的用户
        if(one1==null){
            Users one = iUsersService.getOne(new QueryWrapper<Users>().eq("username", oriusername));
            one.setAttr(attrpath);
            one.setUsername(username);
            boolean b = iUsersService.updateById(one);
            if (b) {
                return ResultVo.ok("200", "更改用户信息成功");
            } else {
                return ResultVo.ok("-200", "更改用户信息失败");
            }
        }else{
            return ResultVo.ok("-200", "重名了，请修改成其他用户名");
        }

    }

    @GetMapping("/downattr")
    public void download(String filename, HttpServletResponse response) throws IOException {
//        QueryWrapper<Users> wrapper = new QueryWrapper<>();
//        wrapper.eq("username", username);
//        Users one = iUsersService.getOne(wrapper);
//        String filename = one.getAttr();
        String realPath = "/opt/userattr/";
//        String realPath = "D:\\pic2304\\";

        IOUtils.copy(new FileInputStream(realPath + filename), response.getOutputStream());
    }


    @PostMapping("/receive")
    private ResultVo receive(@RequestBody Users users) {

        //不是置空 是不改数据
        users.setSalt(null);
        users.setUsername(null);
        users.setPassword(null);
        users.setRole(null);
        users.setAttr(null);
        users.setNickname(null);

        usersMapper.updateById(users);

        return ResultVo.ok("200", "权限修改成功");
    }


    @GetMapping("/register")
    public LoginVo register(String username, String password, String nickname) {
        if (username.equals("") || password.equals("")) {
            return new LoginVo(-1, "必传参数为空", null);
        }
        boolean flag = iUsersService.regist(username, password, nickname);
        if (flag) {
            return new LoginVo(1, "ok", null);
        } else {
            return new LoginVo(-1, "用户名重复", null);
        }
    }

    @GetMapping("/login")
    public LoginVo login(String username, String password) {
        log.info("登录接口接收到参数username={}，password={}", username, password);
        if (username == null || username.equals("")) {//如果传来的用户名是null，或者空字符串，throw一个错误
            throw new RuntimeException("用户名不合法");
        }
        if (password == null || password.equals("")) {//如果传来的密码是null，或者空字符串，throw一个错误
            throw new RuntimeException("密码不能为空");
        }
        LoginVo LoginVo = iUsersService.login(username, password);
        return LoginVo;
    }

    @PostMapping("/edit")
    public ResultVo edit(MultipartFile file) throws IOException {
        String fileaddress = "D:\\pic2304\\";
        String originalFilename = file.getOriginalFilename();
        String filepath = fileaddress + originalFilename;
        File file1 = new File(filepath);
        System.out.println(file1 + "file");
        file.transferTo(file1);
        Users users = new Users();
        users.setId(5);
        users.setAttr(file1.toString());
        boolean b = iUsersService.updateById(users);
        return ResultVo.ok("1", "上传图片成功", fileaddress);
    }

    @PostMapping("/add")
    public ResultVo add(@RequestBody Users user){

        usersMapper.insert(user);

        return ResultVo.ok("200", "增加成功");
    }

    @PostMapping("/delete")
    public ResultVo delete(@RequestBody Users users){
        usersMapper.deleteById(users.getId());
        return  ResultVo.ok("200","删除成功");
    }

    @PostMapping("/update")
    private ResultVo update(@RequestBody Users users){
        QueryWrapper<Users> wrapper = new QueryWrapper<>();
        wrapper.eq(users.getId()!=null,"id",users.getId());
        usersMapper.update(users,wrapper);


        usersMapper.update(users,wrapper);
        return ResultVo.ok("200","修改成功");
//        iUsersService.updateById(users);
//        return ResultVo.ok("200","修改管理员用户成功",users);
    }

    @PostMapping("/select")
    private ResultVo select(@RequestBody Users users) {

        QueryWrapper<Users> wrapper = new QueryWrapper<>();
        wrapper.eq(users.getId()!=null,"id",users.getId())
                .eq(users.getUsername()!=null,"username",users.getUsername());
        List<Users> data = iUsersService.list(wrapper);
        return ResultVo.ok("200", "搜索管理员用户成功", data);
    }

    @GetMapping("/getlist")
    public ResultVo getlist(Integer pageNum, Integer limit) {
        List<Users> page = iUsersService.getlist(pageNum, limit);

        return ResultVo.ok("1", "所有管理员用户信息分页", page);
    }

    @GetMapping("/list")
    public ResultVo userslist() {
        //1.打印日志
//        log.info("订单");
        //2.进行必要的参数校验
        //3.通过service层的对象进行业务处理
        List<Users> orderlist = iUsersService.List();
        //4.返回json
        return ResultVo.ok("200", "列表信息", orderlist);
    }
}
